package com.qingxin.park.action;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qingxin.park.entity.Company;
import com.qingxin.park.service.CompanyService;
import com.qingxin.sys.action.BaseAction;
import com.qingxin.sys.entity.SysGroup;
import com.qingxin.sys.mvc.PageParam;
import com.qingxin.sys.mvc.SysError;
import com.qingxin.sys.service.SysGroupService;
import com.qingxin.sys.support.UploadFile;
import com.qingxin.sys.utils.StringUtils;

@Controller
@RequestMapping("/company")
public class CompanyAction extends BaseAction {

	@Autowired
	private CompanyService companyService;
	
	@Autowired
	private SysGroupService sysGroupService;
	
	
	
	@RequestMapping(value="/getCompanyData.json" , method={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public Object getCompanyData(String groupid, HttpServletRequest request){
		if(StringUtils.isNotEmpty(groupid)){
			SysGroup group = sysGroupService.get(groupid);
			if(group.getGrouptype() == 3){
				groupid = group.getPid();
			}
		}
		return companyService.getCompanyData(groupid, getLoginUser(request));
	}
	
	
	
	/**
	 * 列表
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/list.do", method=RequestMethod.GET)
	public String list(ModelMap model, HttpServletRequest request){
		return "trace/company/company_list";
	}
	
	/**
	 * 列表数据
	 * @param search
	 * @param user_type
	 * @param user_status
	 * @param regionid
	 * @param pageParam
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/listdata.json", method={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public Object listdata(String datatype, String leftdata, String search, String companytype, String companyid, PageParam pageParam, HttpServletRequest request){
		String groupid = "";
		if("GROUP".equalsIgnoreCase(datatype) && StringUtils.isNotEmpty(leftdata) && !"0".equals(leftdata)){
			groupid = leftdata;
		}
		
		return companyService.list(groupid, search, companytype, companyid, pageParam, getLoginUser(request));
	}
	
	
	/**
	 * 添加企业信息
	 * @param model
	 * @param leftdata
	 * @param datatype
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/add.do" , method=RequestMethod.GET)
	public String add(ModelMap model, String datatype, String leftdata, HttpServletRequest request){
		if("GROUP".equalsIgnoreCase(datatype) && StringUtils.isNotEmpty(leftdata) && !"0".equals(leftdata)){
			model.put("groupid", leftdata);
			
			SysGroup group = sysGroupService.get(leftdata);
			if(group.getGrouptype() != 2){
				model.put("errormessage", "该分组【"+group.getGroupname()+"】不是一个企业类型分组，不能在该分组下创建企业信息");
				return "sys/error/error";
			}
			
			Company company = companyService.getByProperty("groupid", leftdata);
			if(company != null){
				model.put("errormessage", "该分组【"+group.getGroupname()+"】已存在企业信息，不能在该分组下重复创建企业信息");
				return "sys/error/error";
			}
			
			
		}else{
			model.put("groupid", "");
		}
		return "trace/company/company_add";
	}
	
	
	/**
	 * 保存企业信息
	 * @param company
	 * @param result
	 * @param typeid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/save.json", method={RequestMethod.POST})
	@ResponseBody
	public Object save(@Valid Company company, BindingResult result, HttpServletRequest request){
		if(result.hasErrors()){
			return getSysErrors(result);
		}
		//System.out.println(company.getGroupid());
		String companyMax = companyService.getCompanyNoMax();
		if(StringUtils.isNotEmpty(companyMax)){
			int number = Integer.parseInt(companyMax)+1;
			String maxNo = number+"";
			if(maxNo.length()==1){
				maxNo = "00"+maxNo;
			}else if(maxNo.length()==2){
				maxNo = "0"+maxNo;
			}
			company.setCompanyNo(maxNo);
		}else{
			company.setCompanyNo("001");
		}
		
		SysError info = companyService.add(company, getLoginUser(request), request);
		return info;
	}
	
	
	/**
	 * 修改企业信息
	 * @param model
	 * @param companyid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/edit.do" , method=RequestMethod.GET)
	public String edit(ModelMap model, String companyid, HttpServletRequest request){
		Company company = companyService.get(companyid);
		model.put("company", company);
		return "trace/company/company_edit";
	}
	
	
	/**
	 * 保存修改的信息
	 * @param company
	 * @param result
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/update.json", method={RequestMethod.POST})
	@ResponseBody
	public Object update(@Valid Company company, BindingResult result, HttpServletRequest request){
		if(result.hasErrors()){
			return getSysErrors(result);
		}
		
		SysError info = companyService.update(company, getLoginUser(request), request);
		return info;
	}
	
	
	
	/**
	 * 删除企业信息
	 * @param materialid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/delete.json", method={RequestMethod.POST})
	@ResponseBody
	public Object delete(String[] companyid, HttpServletRequest request){
		if(companyid==null || companyid.length==0){
			return new SysError("没有选择任何信息.");
		}
		return companyService.delete(companyid, getLoginUser(request), request);
	}
	
	
	/**
	 * 判断企业名称是否存在
	 * @param blockName
	 * @param blockid
	 * @param parkid
	 * @return
	 */
	@RequestMapping(value="/isNameDuplicate.json" , method=RequestMethod.GET)
	@ResponseBody
	public String isNameDuplicate(String companyName, String companyid){
		boolean existed = companyService.isNameDuplicate(companyName, companyid);
		return existed ? "1":"0";
	}
	
	
	/**
	 * 判断企业编号是否存在
	 * @param blockCode
	 * @param blockid
	 * @param parkid
	 * @return
	 */
	@RequestMapping(value="/isNoDuplicate.json" , method=RequestMethod.GET)
	@ResponseBody
	public String isCodeDuplicate(String companyNo, String companyid){
		boolean existed = companyService.isCodeDuplicate(companyNo, companyid);
		return existed ? "1":"0";
	}
	
	
	/**
	 * 设置坐标点
	 * @param model
	 * @param type 坐标点类型
	 * @param id 坐标点ID，可能为空
	 * @param lng
	 * @param lat
	 * @param view 是否查看模式
	 * @return
	 */
	@RequestMapping(value="/setMapCompany.do", method=RequestMethod.GET)
	public String setparkmap(ModelMap model, String id, String view){
		model.put("id", id==null ? "" : id);
		model.put("view", view==null ? false : view);
		
		if(StringUtils.isNotEmpty(id)){
			Company company = companyService.get(id);
			/*if(company != null){
				 company = new Company(company.getCompanyid(),company.getCompanyName(),company.getLat(), company.getLng());*/
				model.put("company", company);
			
		}
		
		return "trace/company/setMapCompany";
	}
	
	
	/**
	 * 企业分布地图
	 * @param model
	 * @param datatype
	 * @param leftdata
	 * @param request
	 * @return
	 */
	/*@RequestMapping(value="/parkmap.do", method=RequestMethod.GET)
	public String parkmap(ModelMap model, String datatype, String leftdata, HttpServletRequest request){
		if(SystemCfg.UI_DATATYPE_PARK.equals(datatype)){
			model.put("parkid", leftdata);
			Company company = companyService.get(leftdata);
			if(company != null){
				MapMarker marker = new MapMarker(park.getParkid(), "park", park.getParkName(), park.getRemark(), park.getLat(), park.getLng());
				model.put("marker", marker);
			}
		}
		
		return "trace/parkmap/parkmap";
	}
	
	
	*//**
	 * 获取要在地图上显示的坐标信息
	 * @param parkid
	 * @param wlng 左边界经度
	 * @param elng 右边界经度
	 * @param nlat 上边界纬度
	 * @param slat 下边界纬度
	 * @param zoom 地图缩放级别
	 * @param size 最多加载条数，小于等于0时表示不限制
	 * @param type
	 * @param markerid
	 * @param token
	 * @param request
	 * @return
	 *//*
	@RequestMapping(value="/loadMapCompany.json", method={RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Object loadMapCompanys(String companyid, BigDecimal wlng, BigDecimal elng,
			BigDecimal nlat, BigDecimal slat, Integer zoom, Integer size,
			String type, String markerid, String token, HttpServletRequest request){
		Map<String, Object> rsmap = new HashMap<String, Object>();
		rsmap.put("token", token);
		
		if(size == null){
			size = 0;
		}
		//企业列表
		List<MapCompany> parkList = companyService.listMapCompany(wlng, elng, nlat, slat, zoom, getLoginUser(request));
		rsmap.put("list", parkList);
		return rsmap;
	}
	
	*//**
	 * 获取指定坐标点的详细信息
	 * @param type 坐标点类型
	 * @param id 坐标点ID
	 * @return
	 *//*
	@RequestMapping(value="/getMapCompany.json", method={RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Object getMapCompany(String id){
		
			Company company = companyService.get(id);
			if(company != null){
				Company company = new Company(company.getCompanyid(),company.getCompanyName(), company.getLat(), company.getLng());
				return company;
			
		}
		return null;
	}*/
	
	/**
	 * 生成二维码
	 * @param model
	 * @param companyid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/qrCode.do" , method=RequestMethod.GET)
	public String qrcode(ModelMap model, String companyid, HttpServletRequest request){
		Company company = companyService.get(companyid);
		model.put("company", company);
		
		//企业二维码规则  第一位：为 5  +时间8位 + 企业编码3位 + 2位随机 + 1位校验
		if( company.getQrcode()==null || company.getQrcode().equals("") ){
			int cishu = 0;
			while(true){
				cishu++;
				String qiyecode = "5";
				
				//日期8位
				String dateString = new SimpleDateFormat("yyyyMMdd").format(new Date());
				//随机两位
				int mathNo = (int)(Math.random()*90)+10;
				
				if(StringUtils.isEmpty(company.getCompanyNo())){
					break;
				}
				qiyecode += dateString+company.getCompanyNo()+mathNo;
				
				int codeInt = 0;
				for(int j= 0;j<qiyecode.length();j++){
					codeInt += Integer.parseInt(qiyecode.charAt(j)+"");
				}
				String jiaoyan = String.valueOf(codeInt % 10);
				qiyecode = qiyecode + jiaoyan;
				
				Company companyCode = companyService.getByProperty("qrcode", qiyecode);
				if(companyCode == null){
					company.setQrcode(qiyecode);
					companyService.update(company,getLoginUser(request), request);
					break;
				}
				if(cishu==5){
					break;
				}
			}
			//return "trace/company/company_qrcode";
		}
		
		model.put("qrcode_url", UploadFile.getDomain()+"/mq/"+company.getQrcode());
		
		return "trace/company/company_qrcodeShow";
	}
	
	/**
	 * 生成保存二维码
	 * @param company
	 * @param result
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/qrCode.json", method={RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Object qrCode(@Valid Company company,String qrCode, HttpServletRequest request){
		SysError info = companyService.updateQrCode(company,qrCode,getLoginUser(request), request);
		return info;
	}
	
	/**
	 * 查看二维码
	 * @param model
	 * @param companyid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/qrCodeShow.do" , method=RequestMethod.GET)
	public String qrcodeShow(ModelMap model, String companyid, HttpServletRequest request){
		Company company = companyService.get(companyid);
		model.put("company", company);
		if(company.getQrcode()==null || company.getQrcode().equals("")){
			return "trace/company/company_qrcode" ;
		}
		
		model.put("qrcode_url", UploadFile.getDomain()+"/mq/"+company.getQrcode());
		
		return "trace/company/company_qrcodeShow";
	}
	

	@RequestMapping(value="/isqrCodeDuplicate.json" , method=RequestMethod.GET)
	@ResponseBody
	public String isqrCodeDuplicate(String groupid, String qrCode){
		boolean existed = companyService.isqrCodeDuplicate(groupid, qrCode);
		return existed ? "1":"0";
	}
	

}
